<template>
  <ve-card
    :title="'合同编号：' + (record.contractNo || '-')"
    :sub-title="record.contractStatusName"
    :type="
      record.contractStatus == 1 || record.contractStatus == -2
        ? 'gray'
        : record.contractStatus == 2
        ? 'blue'
        : record.contractStatus == 3 || record.contractStatus == 10
        ? 'green'
        : record.contractStatus == 4 ||
          record.contractStatus == 5 ||
          record.contractStatus == 6 ||
          record.contractStatus == 7 ||
          record.contractStatus == 8 ||
          record.contractStatus == 11 ||
          record.contractStatus == -1
        ? 'pink'
        : record.contractStatus == 9
        ? 'purple'
        : 'gray'
    "
  >
    <ve-cell label="关联单号" @click="toOrder(record)" style="color: rgba(24, 144, 255, 1)"
      ><span style="color: rgba(24, 144, 255, 1)">{{ record.orderCode || '-' }}</span></ve-cell
    >
    <ve-cell label="所属门店">{{ record.siteName || '-' }}</ve-cell>
    <ve-cell label="业务类型">{{ record.orderTypeName || '-' }}</ve-cell>
    <ve-cell label="合同类型">{{ record.contractTypeName || '-' }}</ve-cell>
    <ve-cell label="合同模板名称">{{ record.templateName || '-' }}</ve-cell>
    <ve-cell label="客户类型">{{ record.leaseType == 1 ? '企业' : '个人' }}</ve-cell>
    <ve-cell label="客户信息">{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</ve-cell>
    <ve-cell label="收费标准">{{ record.chargeAmount || '-' }}元</ve-cell>
    <ve-cell label="发起人">{{ record.startPersonName || '-' }}</ve-cell>
    <ve-cell label="发起签署时间">{{ record.startTime || '-' }}</ve-cell>
    <ve-cell label="完成签署时间">{{ record.lesseeSignTime || '-' }}</ve-cell>
    <ve-cell label="创建方式">{{ record.createWayName || '-' }}</ve-cell>

    <!-- 签署中 -->
    <block v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
      <ve-cell label="承租方" class="person-flex">
        <view>{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</view>
        <view class="person-flex-copy" v-if="record.lesseeSignStatusName">
          <view :class="['tag', record.lesseeSignStatus == 1 ? 'text-no' : 'text-yes']">{{ record.lesseeSignStatusName || '-' }}</view>
        </view>
        <view class="copys" @click="copylink(record, 2)" v-if="usePermission('svmsapp:contract.CopySigningLink')">
          <image class="image-icon" src="@/static/icons/link.png" mode="widthFix"></image>
          <view class="copy-text">复制合同链接</view>
        </view>
      </ve-cell>
      <ve-cell label="出租方" class="person-flex">
        <view>{{ record.tenantName || '-' }}</view>
        <view class="person-flex-copy" v-if="record.hireSignStatusName">
          <view :class="['tag', record.hireSignStatus == 1 ? 'text-no' : 'text-yes']">{{ record.hireSignStatusName || '-' }}</view>
        </view>
      </ve-cell>
    </block>

    <!-- 作废中 -->
    <block v-if="record.contractStatus == 7">
      <ve-cell label="承租方" class="person-flex">
        <view>{{ record.leaseType == 1 ? record.lesseeCompanyName || '-' : record.lesseeName || '-' }}</view>
        <view class="person-flex-copy" v-if="record.lesseeInvalidedStatusName">
          <view :class="['tag', record.lesseeInvalidedStatus == 1 ? 'text-no' : 'text-yes']">{{
            record.lesseeInvalidedStatusName || '-'
          }}</view>
        </view>
        <view
          class="copys"
          @click="copylink(record, 7)"
          v-if="record.lesseeInvalidedStatus == 1 && usePermission('svmsapp:contract.CopyVoidLink')"
        >
          <image class="image-icon" src="@/static/icons/link.png" mode="widthFix"></image>
          <view class="copy-text">复制作废链接</view>
        </view>
      </ve-cell>

      <ve-cell label="出租方" class="person-flex">
        <view>{{ record.tenantName || '-' }}</view>
        <view class="person-flex-copy" v-if="record.hireInvalidedStatusName">
          <view :class="['tag', record.hireInvalidedStatus == 1 ? 'text-no' : 'text-yes']">{{
            record.hireInvalidedStatusName || '-'
          }}</view>
        </view>
      </ve-cell>
    </block>

    <ve-operate-list :operates="operates" :record="record" />
    <ve-popup :model-value="popupValue" @close="close" mode="bottom" :maskClose="true">
      <view class="add-popup">
        <view class="title">请选择</view>
        <ve-button class="button" size="default" @click="toPreview(record)" style="margin-bottom: 32rpx; background: #d5e3ff"
          >下载PDF文件</ve-button
        >
        <ve-button class="button" size="default" @click="toDownload(record)">下载JPG图片(合成长图)</ve-button>
      </view>
    </ve-popup>
  </ve-card>

  <!-- 填写电话 -->
  <addPhoneModal ref="addphone" @ok="addphoneFn" />
  <!-- 复制弹窗 -->
  <copyModal ref="copymodals" />
</template>

<script setup>
  import { usePermission } from '@/hooks/usePermission'
  import { userStore } from '@/stores'
  import { ref } from 'vue'
  import addPhoneModal from '@/pages/order/components/customer/add-phone.vue'
  import copyModal from '@/pages/order/components/customer/copy-modal.vue'
  import { clientInfoDetail, editClientInfo } from '@/api/market/member'
  import {
    downloadContractFileAPI,
    initiateAPI,
    revokeAPI,
    nullifyAPI,
    invalidAPI,
    getTenantSignUrlAPI,
    determineAPI,
    getLesseeSignUrlAPI,
    deleteContractFileAPI,
    createQysContractAPI,
  } from '@/api/order/contract'
  const userInfoStore = userStore()
  const clientData = ref()
  const addphone = ref(null)
  const copymodals = ref(null)
  defineProps({
    record: {
      type: Object,
    },
  })
  const emits = defineEmits(['resetRefresh'])
  const popupValue = ref(false)
  const isDownload = ref(false)

  // 带回电话
  const addphoneFn = (recordData) => {
    // 补充电话
    if (recordData.type == 'a') {
      // 发起签署
      editClientInfo({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then(() => {
        console.log('编辑企业客户接口 ---- 补充电话')
        // 判断余额
        determineAPI({ orderType: record.orderType, orderNo: record.orderCode }).then((rees) => {
          if (rees.result.determine) {
            // 1.足够
            // 发起签署
            console.log('recordData', recordData)
            initiateFn(recordData.record)
          } else {
            // 2.不够
            uni.showModal({
              title: '提示',
              content: `账户余额不足，请先联系工作人员充值，再进行操作`,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  emits('resetRefresh')
                }
              },
            })
            return false
          }
        })
      })
    }
    if (recordData.type == 'b') {
      // 调用发起作废补充电话的接口
      editClientInfo({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then(() => {
        console.log('编辑企业客户接口 ---- 补充电话')
        // 发起作废
        nullifyFn(recordData.record)
      })
    }
    if (recordData.type == 'c') {
      editClientInfo({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then(() => {
        contractGet(recordData.record)
      })
    }
  }
  // 复制承租方链接
  const copylink = (record, type) => {
    // 获取到链接后 复制
    getLesseeSignUrlAPI({ id: record.id }).then((res) => {
      var tlt = type == 2 ? '已将链接复制到剪切板' : '承租方作废链接已复制到剪切板'
      uni.setClipboardData({
        data: res.result,
        success: function () {
          uni.showToast({
            title: tlt,
            icon: 'none',
          })
        },
      })
    })
  }
  // 发起签署
  const initiateFn = (record) => {
    uni.showModal({
      title: '提示',
      content: '请确认是否要发起合同签署?',
      success: function (res) {
        if (res.confirm) {
          // 发起签署接口
          initiateAPI({ id: record.id }).then(() => {
            // 企业/个人 提示不同
            if (record.leaseType == 1) {
              // 企业
              uni.showModal({
                title: '提示',
                content: '已将合同信息以短信的形式发送至企业联系人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    emits('resetRefresh')
                  }
                },
              })
            } else {
              // 个人
              uni.showModal({
                title: '提示',
                content: '已将合同信息以短信的形式发送至承租人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    emits('resetRefresh')
                  }
                },
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 发起作废
  const nullifyFn = (record) => {
    uni.showModal({
      title: '提示',
      content: '合同已完成签署，确认作废吗?',
      success: function (res) {
        if (res.confirm) {
          // 发起作废接口
          nullifyAPI({ id: record.id }).then(() => {
            // 企业/个人 提示不同
            if (record.leaseType == 1) {
              // 企业
              uni.showModal({
                title: '提示',
                content: '已将作废协议以短信形式发送至企业联系人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    emits('resetRefresh')
                  }
                },
              })
            } else {
              // 个人
              uni.showModal({
                title: '提示',
                content: '已将作废协议以短信形式发送至承租人手机，并等待签署',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    emits('resetRefresh')
                  }
                },
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 列表里点击失败原因
  const errorShow = (record) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      uni.showModal({
        title: '提示',
        content: record.createErrorReason,
        showCancel: false,
        confirmText: '关闭',
      })
    }
  }
  // 生成合同
  const contractGet = (record) => {
    createQysContractAPI({ id: record.id }).then((rees) => {
      console.log(rees)
      if (rees.result.createErrorCode) {
        if (rees.result.createErrorCode == 1001) {
          // 生成失败弹窗
          // 1. 姓名手机号不匹配时
          toError(record)
        } else {
          // 生成失败弹窗
          // 2. 其他原因（没有前往修改按钮）
          uni.showModal({
            title: '提示',
            content: record.createErrorReason,
            showCancel: false,
            confirmText: '关闭',
          })
          emits('resetRefresh')
        }
      } else if (rees.result.createErrorCode == null) {
        uni.showToast({
          title: '操作成功',
          icon: 'none',
        })
        emits('resetRefresh')
      }
    })
  }
  // 失败弹窗
  const toError = (record) => {
    uni.showModal({
      title: '提示',
      content: record.createErrorReason,
      confirmText: '前往修改',
      success: function (res) {
        if (res.confirm) {
          // 关闭当前页,跳转修改订单页面
          if (record.orderType == 1) {
            uni.navigateTo({
              url: '/pages/order/short-order/form/edit?id=' + record.orderId,
            })
          } else {
            uni.navigateTo({
              url: '/pages/order/long-order/form/edit?id=' + record.orderId,
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 刷新列表调用    emits('resetRefresh')
  const operates = ref([
    {
      label: '发起作废',
      permission: 'svmsapp:contract.InitiateCancellation',
      show: (record) => record.contractStatus == 3,
      method: (record) => {
        if (record.leaseType == 1) {
          // 企业
          clientInfoDetail({ id: record.lesseeId }).then((res) => {
            clientData.value = res.result
            if (res.result.mobile && res.result.linkman) {
              // 1.有企业手机号
              nullifyFn(record)
            } else {
              // 2.没有企业手机号, 发起手机号填写弹窗
              addphone.value.open(record, 'b', clientData.value)
            }
          })
        } else {
          // 个人
          nullifyFn(record)
        }
      },
    },
    {
      label: '预览',
      show: (record) =>
        record.contractStatus != 9 &&
        record.contractStatus != 10 &&
        record.contractStatus != 11 &&
        record.contractStatus != -1 &&
        record.contractStatus != -2,
      permission: 'svmsapp:contract.Preview',
      method: (record) => {
        toPreview(record)
      },
    },
    {
      label: '无需签署',
      permission: 'svmsapp:contract.NoNeedSign',
      show: (record) => record.contractStatus == 1 || record.contractStatus == -1 || record.contractStatus == -2,
      method: (record) => {
        uni.showModal({
          title: '提示',
          content: '请确认当前合同是否无需签署，无需签署的合同将变为无效状态，并且当前合同不会重新生成',
          success: function (res) {
            if (res.confirm) {
              // 调用失效接口
              invalidAPI({ id: record.id }).then((res) => {
                // 刷新列表
                emits('resetRefresh')
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '生成电子合同',
      show: (record) => record.contractStatus == -2,
      permission: 'svmsapp:contract.Getcontract',
      method: (record) => {
        console.log(record)
        uni.showModal({
          title: '提示',
          content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
          success: function (res) {
            if (res.confirm) {
              // 客户类型为企业客户
              if (record.leaseType == 1) {
                // 判断是否填写企业联系人的手机号
                clientInfoDetail({ id: record.lesseeId }).then((rees) => {
                  clientData.value = rees.result
                  if (rees.result.mobile && rees.result.linkman) {
                    // 1.有企业手机号
                    contractGet(record)
                  } else {
                    // 2.没有企业手机号, 发起手机号填写弹窗
                    addphone.value.open(record, 'c', clientData.value)
                  }
                })
              } else {
                // 客户类型为个人会员
                contractGet(record)
              }
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '重新生成',
      show: (record) => record.contractStatus == -1,
      permission: 'svmsapp:contract.Getagain',
      method: (record) => {
        console.log(record)
        uni.showModal({
          title: '提示',
          content: '电子合同生成后，修改订单或费用都不会更新此合同内的信息，请确认是否生成？',
          success: function (res) {
            if (res.confirm) {
              contractGet(record)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
    },
    {
      label: '撤回',
      permission: 'svmsapp:contract.Withdraw',
      show: (record) => record.contractStatus == 2,
      method: (record) => {
        if (record.lesseeSignStatus == 1 || record.hireSignStatus == 1) {
          uni.showModal({
            title: '提示',
            content: '合同撤回后，承租方短信失效，无法完成签署，确认撤回吗？',
            success: function (res) {
              if (res.confirm) {
                revokeAPI({ id: record.id }).then(() => {
                  uni.showToast({
                    title: '操作成功',
                    icon: 'none',
                  })
                  emits('resetRefresh')
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            },
          })
        } else if (record.orderStatus == -100 || record.orderStatus == -1000) {
          revokeAPI({ id: record.id }).then(() => {
            uni.showToast({
              title: '操作成功',
              icon: 'none',
            })
            emits('resetRefresh')
          })
        }
      },
    },
    {
      label: '去作废',
      permission: 'svmsapp:contract.contractToCancel',
      show: (record) =>
        record.signWay == 1 && record.contractStatus == 7 && record.lesseeInvalidedStatus == 2 && record.hireInvalidedStatus == 1,
      method: (record) => {
        getTenantSignUrlAPI({ id: record.id }).then((res) => {
          console.log(res)
          // 复制链接
          uni.setClipboardData({
            data: res.result,
            success: function () {
              copymodals.value.open('b')
            },
          })
        })
      },
    },
    {
      label: '发起签署',
      permission: 'svmsapp:contract.InitiateSigning',
      show: (record) => record.contractStatus == 1,
      method: (record) => {
        // 客户类型为企业客户
        if (record.leaseType == 1) {
          // 判断是否填写企业联系人的手机号
          clientInfoDetail({ id: record.lesseeId }).then((rees) => {
            clientData.value = rees.result
            if (rees.result.mobile && rees.result.linkman) {
              // 1.有企业手机号
              // ①判断余额(接口判断)
              determineAPI({ orderType: record.orderType, orderNo: record.orderCode }).then((ress) => {
                if (ress.result.determine) {
                  // 1.足够
                  initiateFn(record)
                } else {
                  // 2.不够
                  uni.showModal({
                    title: '提示',
                    content: '账户余额不足，请先联系工作人员充值，再进行操作',
                    showCancel: false,
                    success: function (resss) {
                      if (resss.confirm) {
                        // 无后续操作
                      }
                    },
                  })
                  return false
                }
              })
            } else {
              // 2.没有企业手机号, 发起手机号填写弹窗
              addphone.value.open(record, 'a', clientData.value)
            }
          })
        } else {
          // 客户类型为个人会员
          // 判断合同账户余额是否足够
          determineAPI({ orderNo: record.orderCode, orderType: record.orderType }).then((res) => {
            if (res.result.determine) {
              // 1.足够
              initiateFn(record)
            } else {
              // 2.不够
              uni.showModal({
                title: '提示',
                content: '账户余额不足，请先联系工作人员充值，再进行操作',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    // 无后续操作
                  }
                },
              })
              return false
            }
          })
        }
      },
    },
    {
      label: '去签署',
      permission: 'svmsapp:contract.GoSigning',
      show: (record) => record.signWay == 1 && record.contractStatus == 2 && record.lesseeSignStatus == 2 && record.hireSignStatus == 1,
      method: (record) => {
        if (record.signWay == 1) {
          getTenantSignUrlAPI({ id: record.id }).then((res) => {
            uni.setClipboardData({
              data: res.result,
              success: function () {
                copymodals.value.open('a')
              },
            })
          })
        }
      },
    },
    {
      label: '原因',
      permission: '',
      show: (record) => record.contractStatus == -1,
      method: (record) => {
        // 生成失败弹窗
        errorShow(record)
      },
    },
    {
      label: '下载',
      permission: 'svmsapp:contract.download',
      show: (record) => record.contractStatus == 3 || record.contractStatus == 8 || record.contractStatus == 7,
      method: (record) => {
        openPopup()
      },
    },
  ])

  // 跳转业务单详情
  const toOrder = (record) => {
    const { orderType, orderId } = record
    if (orderType == 1) {
      if (usePermission('svmsapp:order:short-order.view')) {
        uni.navigateTo({
          url: '/pages/order/short-order/detail/index?id=' + orderId,
        })
      }
    } else {
      if (usePermission('svmsapp:order:long-order.view')) {
        uni.navigateTo({
          url: '/pages/order/long-order/detail/index?id=' + orderId,
        })
      }
    }
  }

  // 预览
  const toPreview = (record) => {
    downloadContractFileAPI({ id: record.id, contractFileType: 1 }).then((r) => {
      if (!r.result) {
        uni.showToast({
          title: '打开失败',
          icon: 'none',
        })
        return false
      }
      uni.downloadFile({
        url: r.result,
        success: function (res) {
          const filePath = res.tempFilePath
          uni.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
              // 销毁文件
              record.payType == 1 && deleteContractFileAPI({ contractFilePath: r.result })
            },
          })
        },
      })
    })
  }

  // 下载
  const toDownload = (record) => {
    if (!isDownload.value) {
      isDownload.value = true
      downloadContractFileAPI({ id: record.id, contractFileType: 2 }).then((r) => {
        isDownload.value = false
        if (!r.result) {
          uni.showToast({
            title: '下载失败',
            icon: 'none',
          })
          return false
        }
        uni.saveImageToPhotosAlbum({
          filePath: r.result,
          success: function () {
            uni.showToast({
              title: '已保存至相册',
              icon: 'none',
            })
            close()
          },
          fail: function (fail) {
            uni.showToast({
              title: fail.errMsg.includes('Permission') ? '无相册访问权限，无法下载' : '下载失败',
              icon: 'none',
            })
            close()
          },
        })
      })
    }
  }

  const openPopup = () => {
    popupValue.value = true
  }
  const close = () => {
    popupValue.value = false
  }
</script>

<style lang="less" scoped>
  .card-footer {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .card-footer {
      width: 100%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
      padding: 32rpx 0;

      .operate-list {
        width: 100%;
        font-size: 28rpx;
        font-weight: 400;
        color: #8491a8;
      }

      .ve-button {
        margin-left: 24rpx;
        margin-bottom: 24rpx;
      }
    }
  }
  .person-flex {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    view:nth-child(1) {
      max-width: 280rpx;
    }
    .person-flex-copy {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-left: 16rpx;
      .tag {
        padding: 0 16rpx;
        height: 40rpx;
        line-height: 40rpx;
        border-radius: 347rpx;
        font-size: 24rpx;
        margin-right: 24rpx;
      }
      .text-no {
        background: #fff7e8;
        color: #ff7d00;
      }
      .text-yes {
        background: #e8ffea;
        color: #00b42a;
      }
    }
  }
  .copys {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .image-icon {
      width: 28rpx;
      height: 28rpx;
      margin: 0 6rpx 0 0;
    }
    .copy-text {
      color: #3072f6;
      font-size: 26rpx;
      font-weight: 400;
    }
  }
  :deep(.ve-cell-content) {
    flex-wrap: wrap;
  }
  .add-popup {
    padding: 0 40rpx 96rpx 40rpx;
    .title {
      font-weight: 600;
      font-size: 36rpx;
      color: #191c27;
      line-height: 44rpx;
      text-align: center;
      padding: 32rpx 0 48rpx 0;
    }
  }
</style>
